#!/bin/bash

#1 获取输入参数个数，如果没有参数，直接退出
FILE_COUNT=$#
if((FILE_COUNT==0)); then
    echo ">>> 错误：未传递文件参数！"
    echo "  用法：mysql5719_slave_docker.sh rootPassword"
    exit;
fi
MYSQL_ROOT_PASSWORD=$1
# 创建数据目录
MODULE_PATH=/opt/module/mysql5719/slave
SLAVE_DOCKER_NAME=mysql5719_slave
# 删除数据目录及窗器
rm -rf $MODULE_PATH
if(( `docker ps -a | grep $SLAVE_DOCKER_NAME | wc -l` >0 ));then
    docker rm -f $SLAVE_DOCKER_NAME
fi

# 创建数据目录
for folder in "data" "logs" "config"; do
    if [ ! -d "$MODULE_PATH/$folder" ]; then
        mkdir -p $MODULE_PATH/$folder
        chmod 777 $MODULE_PATH/$folder
    fi
done

sudo cat >$MODULE_PATH/config/my.cnf<<EOF
# 从库
[mysqld]
#服务id，不可重复
server-id=2
sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
EOF

# 启动容器
docker run -d \
    --privileged=true \
    -v /etc/localtime:/etc/localtime:ro \
    -e TZ=Asia/Shanghai \
    -p 3307:3306 \
    --name $SLAVE_DOCKER_NAME \
    -e MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD \
    -v $MODULE_PATH/data:/var/lib/mysql \
    -v $MODULE_PATH/logs:/var/log/mysql \
    -v $MODULE_PATH/config/my.cnf:/etc/mysql/conf.d/my.cnf \
    mysql:5.7.19

# 查看状态
docker logs $SLAVE_DOCKER_NAME
echo "从库登录用户名：root，密码：$MYSQL_ROOT_PASSWORD"


